package com.kaoyaya.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import com.kaoyaya.delivery.data.DateTest;

import android.util.Log;

/**
 * HTTP请求工具类
 * @author Goven
 * @date 2012-12-12
 */
public class HttpUtil {

	/**
	 * 普通post方法请求
	 * @param url 请求地址
	 * @param params 请求参数，可以为空
	 * @return 返回请求的结果
	 */
	public static String doPost(String url, Map<String, Object> params) {
		String result = null;
		try {
			List<NameValuePair> postParams = new ArrayList<NameValuePair>();
			if (params != null) {
				for (Map.Entry<String, Object> entry : params.entrySet()) {
					postParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
				}
			}
			HttpEntity httpEntity = new UrlEncodedFormEntity(postParams, "utf-8");
			HttpPost httpPost = new HttpPost(url);
			httpPost.setEntity(httpEntity);

			HttpParams httpParams = new BasicHttpParams();
			HttpConnectionParams.setConnectionTimeout(httpParams, 5000);
			HttpConnectionParams.setSoTimeout(httpParams, 5000);

			HttpClient httpClient = new DefaultHttpClient(httpParams);
			HttpResponse httpResponse = httpClient.execute(httpPost);

			int stateCode = httpResponse.getStatusLine().getStatusCode();
			if (stateCode == HttpStatus.SC_OK) {
				result = EntityUtils.toString(httpResponse.getEntity(), "utf-8");
			}
		} catch (Exception e) {
			Log.e("HttpUtil (doPost) --> ", e.toString());
		}
		return result;
	}

	/**
	 * post请求方法，除了传递字符参数，还可以传递File对象参数
	 * @param url 请求地址
	 * @param params 参数集
	 * @param file File对象
	 * @return 返回请求的结果
	 */
	public static String doMultiPost(String url, Map<String, String> params, File file) {
		String result = null;
		try {
			MultipartEntity multiEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
			for (Map.Entry<String, String> entry : params.entrySet()) {
				multiEntity.addPart(entry.getKey(), new StringBody(entry.getValue(), Charset.forName("utf-8")));
			}
			if (file != null) {
				multiEntity.addPart("file", new FileBody(file));
			}
			HttpPost httpPost = new HttpPost(url);
			httpPost.setEntity(multiEntity);

			HttpParams httpParams = new BasicHttpParams();
			HttpConnectionParams.setConnectionTimeout(httpParams, 5000);
			HttpConnectionParams.setSoTimeout(httpParams, 5000);

			HttpClient httpClient = new DefaultHttpClient(httpParams);
			HttpResponse httpResponse = httpClient.execute(httpPost);

			int stateCode = httpResponse.getStatusLine().getStatusCode();
			if (stateCode == HttpStatus.SC_OK) {
				result = EntityUtils.toString(httpResponse.getEntity(), "utf-8");
			}
		} catch (Exception e) {
			Log.e("HttpUtil (doMultiPost) --> ", e.toString());
		}
		return result;
	}
	
	/**
	 * WebService访问方法
	 * @param methodName 方法名
	 * @param params 参数
	 * @return 请求结果字符串
	 * @author Goven
	 * @date 2013-1-4
	 */
	public static String doWS(boolean isNetWs, String wsdlLocation, String methodName, Map<String, Object> params) {
		String namespace = null;
		if (isNetWs) namespace = "http://tempuri.org/";
		else namespace = "http://ws.bitcare.com/";
		try {
			// 实例化SoapObject对象,指定webService的命名空间以及调用方法的名称
			SoapObject soapObject = new SoapObject(namespace, methodName);
			// 设置调用方法参数的值
			if (params != null) {
				for (Map.Entry<String, Object> entry : params.entrySet()) {
					soapObject.addProperty(entry.getKey(), entry.getValue());
				}
			}
			// 获得序列化的Envelope
			SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
			envelope.bodyOut = soapObject;
			envelope.setOutputSoapObject(soapObject);
			// 创建HttpTransportSE对象,通过HttpTransportSE类的构造方法可以指定WebService的url
			HttpTransportSE transport = new HttpTransportSE(wsdlLocation, 5000);
			transport.debug = true;
			if (isNetWs) {
				envelope.dotNet = true;
				transport.call(namespace + methodName, envelope);
			} else {
				transport.call(null, envelope);
			}
			// call方法调用WebService方法
			if (envelope.getResponse() != null) {
				return envelope.getResponse().toString();
			}
		} catch (Exception e) {
			Log.e("HttpUtil (doWS) --> ", e.toString());
		}
		return null;
	}
	
	public static String doWS(String wsUrl, String methodName, Map<String, Object> params) {
		boolean isNetWs = false;
		if (wsUrl.contains(".asmx")) {
			isNetWs = true;
		}
		String namespace;
		if (isNetWs) 
			namespace = "http://tempuri.org/";
		else 
			namespace = "http://ws.bitcare.com/";
		try {
			// 实例化SoapObject对象,指定webService的命名空间以及调用方法的名称
			SoapObject soapObject = new SoapObject(namespace, methodName);
			// 设置调用方法参数的值
			if (params != null) {
				for (Map.Entry<String, Object> entry : params.entrySet()) {
					soapObject.addProperty(entry.getKey(), entry.getValue());
				}
			}
			// 获得序列化的Envelope
			SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
			envelope.bodyOut = soapObject;
			envelope.setOutputSoapObject(soapObject);
			// 创建HttpTransportSE对象,通过HttpTransportSE类的构造方法可以指定WebService的url
			HttpTransportSE transport = new HttpTransportSE(wsUrl, 5000);
			transport.debug = true;
			if (isNetWs) {
				envelope.dotNet = true;
				transport.call(namespace + methodName, envelope);
			} else {
				transport.call(null, envelope);
			}
			// call方法调用WebService方法
			if (envelope.getResponse() != null) {
				return envelope.getResponse().toString();
			}
		} catch (Exception e) {
			Log.e("HttpUtil (doWS) --> ", e.toString());
		}
		return null;
	}

	/**
	 * Get请求方法
	 * @param path 请求地址
	 * @param params 请求参数
	 * @return 返回请求的结果
	 */
	public static String doGet(String path, Map<String, String> params) {
		String strResult = "0";
		StringBuilder sb = new StringBuilder(path);
		HttpURLConnection conn = null;
		int stateCode = 0;
		try {
			for (Map.Entry<String, String> entry : params.entrySet()) {
				sb.append(entry.getKey()).append('=').append(entry.getValue()).append('&');
			}
			sb.deleteCharAt(sb.length() - 1);

			URL url = new URL(sb.toString());
			conn = (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(5 * 1000);
			conn.setReadTimeout(5 * 1000); // 设置过期时间为5秒
			conn.setRequestMethod("GET"); // 设置方法为GET
			conn.connect();
			stateCode = conn.getResponseCode();
			if (stateCode == HttpURLConnection.HTTP_OK) {
				// 如果成功返回
				Scanner scanner = new Scanner(conn.getInputStream(), "utf-8");// 以utf-8格式接收，避免中文乱码
				StringBuffer str = new StringBuffer();
				while (scanner.hasNextLine()) {
					str.append(scanner.nextLine());
					str.append("\n");
				}
				strResult = str.toString();
			}
		} catch (Exception e) {
			Log.e("HttpUtil (doGet) --> ", e.toString());
		} finally {
			conn.disconnect();
		}
		return strResult;
	}
	
	/**
	 * 普通下载
	 * @param url 下载地址
	 * @param filePath 保存路径
	 * @return File对象，如果长度为0则返回null
	 * @author Goven
	 * @date 2013-4-23
	 */
	public static File downLoad(String url, String filePath) {
		try {
			URL connUrl = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) connUrl.openConnection();
			conn.setConnectTimeout(30 * 1000);
			conn.setReadTimeout(30 * 1000);
			conn.setDoInput(true);
			conn.connect();

			File file = new File(filePath);
			file.createNewFile();
			InputStream is = conn.getInputStream();
			FileOutputStream fos = new FileOutputStream(file);
			byte[] temp = new byte[1024];
			int i = 0;
			while ((i = is.read(temp)) > 0) {
				fos.write(temp, 0, i);
			}
			fos.close();
			is.close();
			if (file.length() > 0) {
				return file;
			}
		} catch (IOException e) {
			Log.e("HttpUtil (down) --> ", e.toString());
		}
		return null;
	}
	
	public static String readStr(String url) {
		StringBuilder result = new StringBuilder();
		try {
			URL connUrl = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) connUrl.openConnection();
			conn.setConnectTimeout(30 * 1000);
			conn.setReadTimeout(30 * 1000);
			conn.setDoInput(true);
			conn.connect();
			
			InputStreamReader read = new InputStreamReader(conn.getInputStream());
			BufferedReader bufferedReader = new BufferedReader(read);
			String line = null;
			while((line = bufferedReader.readLine()) != null) {
				result.append(line);
			}
			read.close();
		} catch (IOException e) {
			Log.e("HttpUtil (down) --> ", e.toString());
		}
		return result.toString();
	}
	
}
